package com.situation.config;

import com.situation.mapper.LoginLogMapper;
import com.situation.mapper.TbUserMapper;
import com.situation.pojo.DO.TbLoginLog;
import com.situation.pojo.DO.TbUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private LoginLogMapper loginLogMapper;


    public String getName() {
        return "myrealm";
    }


    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户的用户名
        String username = (String) principalCollection.getPrimaryPrincipal();

        //根据用户名查询该用户的所有角色和权限
        List<String> roleList = userMapper.findRoleByUsername(username);
        List<String> permissionList = userMapper.findPermissionByUsername(username);

        //返回当前用户的所有角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleList);
        info.addStringPermissions(permissionList);

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取当前用户的用户名
        String username = (String) authenticationToken.getPrincipal();

        //去数据库中查询该用户
        TbUser user = userMapper.findUserByUsername(username);

        if (user == null) {
            throw new UnknownAccountException(" 账号不存在 ");
        }
        if (user.getStatus() == 0) {
            throw new LockedAccountException(" 账号已被锁定! ");
        }

        String salt = userMapper.findSalt(username);

        return new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(salt), getName());

    }
}
